package com.ef.web.action;

import java.util.Date;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.ef.constant.ConfirmMessage;
import com.ef.domain.MarketingPolicy;
import com.ef.domain.Team;
import com.ef.domain.User;
import com.ef.service.MarketingPolicyService;
import com.ef.util.CustomExample;

public class MarketingPolicyAction extends BaseAction<MarketingPolicy> {

	private static final long serialVersionUID = 1L;
	private MarketingPolicyService marketingPolicyService;

	protected final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
			.getLog(MarketingPolicyAction.class);

	@SuppressWarnings("serial")
	public String list() {

		this.listResult = marketingPolicyService.findByExample(
				new CustomExample<MarketingPolicy>(this.getModel()) {
					public void appendCondition(Criteria criteria) {
						User user =  getSessionUser();
						Team team = null; 
						if (user.getRole() != null
								&& user.getRole().getName().trim().equalsIgnoreCase("MK")) {
							team = user.getTeam();
						}
						if (team != null) {
							criteria.add(Restrictions.eq("team", team));
						}
						this.enableLike(MatchMode.ANYWHERE);
					}
				}, this.getStartIndex(), this.getPageSize());
		return LIST;
	}

	public String edit() {

		return EDIT;
	}

	public String save() {

		MarketingPolicy marketingPolicy = this.getModel();
		String name = marketingPolicy.getName();
		User user = this.getSessionUser();
		if (user.getRole() != null && user.getRole().isMK()) {
			if (user.getTeam() != null) {
				String ac = user.getTeam().getAdultOrChild();
				if (ac.length() > 0 && name.trim().indexOf(ac) < 0) {
					marketingPolicy.setName(name + ac);
					marketingPolicy.setTeam(user.getTeam());
				}
			}
		}
		marketingPolicy.setUpdateTime(new Date());
		marketingPolicy.setUpdateUser(getSessionUser());
		marketingPolicyService.saveOrUpdate(marketingPolicy);
		this.setResult(ConfirmMessage.MarketingPolicy);
		return EDIT;
	}

	public String delete() {
		String ids = getRequest().getParameter("ids");
		String[] id = ids.split(",");
		for (String i : id) {
			marketingPolicyService.delete(marketingPolicyService.findById(Long
					.valueOf(i)));
		}

		return DELETE;
	}
	
	public MarketingPolicyService getMarketingPolicyService() {
		return marketingPolicyService;
	}

	public void setMarketingPolicyService(
			MarketingPolicyService marketingPolicyService) {
		this.marketingPolicyService = marketingPolicyService;
	}
	
	
	
}
